package com.company.project.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.aop.annotation.LogAnnotation;
import com.company.project.common.config.DcicUrlProperties;
import com.company.project.common.exception.BusinessException;
import com.company.project.common.exception.code.BaseResponseCode;
import com.company.project.common.utils.Constant;
import com.company.project.common.utils.DataResult;
import com.company.project.common.utils.PasswordUtils;
import com.company.project.entity.SysUser;
import com.company.project.entity.TeamUserEntity;
import com.company.project.service.HttpSessionService;
import com.company.project.service.TeamUserService;
import com.company.project.service.UserService;
import com.company.project.vo.req.RegisterData;
import com.company.project.vo.resp.LoginDTO;
import com.company.project.vo.resp.LoginFrontRespVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RequestMapping("/front")
@RestController
@Api(tags = "登录注册")
@Slf4j
@EnableConfigurationProperties(DcicUrlProperties.class)
public class FrontController extends BaseController{
	
	@Resource
    private UserService userService;
	
	@Resource
	private TeamUserService teamUserService;
	
	@Resource
    private HttpSessionService httpSessionService;
	
	@Resource
	private DcicUrlProperties dcicUrlProperties;
	
	@PostMapping("/verify")
    @ApiOperation(value = "用户注册")
    @LogAnnotation(title = "登录注册模块", action = "用户注册")
	public DataResult verify(@RequestBody @Valid RegisterData data) {
		//比赛报名是否开启
		if(getMatchStatus()) {
			if (!PasswordUtils.isRegistered(data.getName(), data.getIdNumber(), dcicUrlProperties.getUrl())) {
				throw new BusinessException("成员" + data.getName() + "未在数字中国创新赛平台上注册，或者填写信息错误，请核查！");
			}		
			SysUser user = new SysUser();
			BeanUtils.copyProperties(data, user);
			//注册人员的角色为参赛人员
			List<String> roleIds = new ArrayList<>();
			roleIds.add(Constant.CUSTOMER_ROLE_ID);
			user.setRoleIds(roleIds);
			
			user.setIdNumber(data.getIdNumber().toUpperCase());
			//用户名等同手机号
			user.setUsername(data.getPhone());
			//初始密码身份证后六位
			//user.setPassword(data.getIdNumber().substring(12, 18));
			//生成dcicUserId
			user.setDcicUserId(PasswordUtils.getMD5(data.getName(), data.getIdNumber()));
			userService.addUser(user);
			return DataResult.success();
		}else {
			throw new BusinessException(BaseResponseCode.MATCH_STATUS_STOP);
		}
			
	}
	
	@PostMapping(value = "/login")
	@ApiOperation(value = "用户登录")
	public DataResult login(@RequestBody @Valid LoginDTO vo, HttpServletRequest request) {		
		log.info("用户登录参数："+JSON.toJSONString(vo));
		String captcha = (String) request.getServletContext().getAttribute("captcha");		    
		// 判断验证码
		if (!captcha.equals(vo.getCaptcha())) {			
			return DataResult.fail("验证码错误！");
		}
		LoginFrontRespVO respVO = userService.loginFront(vo);
		TeamUserEntity teamUser = teamUserService
				.getOne(Wrappers.<TeamUserEntity>lambdaQuery().eq(TeamUserEntity::getDcicUserId, respVO.getDcicUserId()));
		if (teamUser != null) {
			respVO.setTeamId(teamUser.getTeamId());
		}
		return DataResult.success(respVO);
	}
}
